<template>
  <div>
    <div class="xw-block" style="display: flex">
      <el-input v-model="pageRequest.q.nickName" style="width: 300px" placeholder="请输入你想搜索的内容？"
                clearable @clear="clearSearch"></el-input>
      <el-button style="margin-left: 20px" type="primary" @click="load">搜索</el-button>
    </div>

    <div class="xw-block" style="display: flex">
      <el-button type="primary" @click="add" style="margin-right: 10px;">新增用户</el-button>
      <el-popconfirm
          style="margin-left: 5px"
          confirm-button-text="确定"
          cancel-button-text="我再想想"
          icon="el-icon-info"
          icon-color="red"
          title="您确定要删除吗？"
          @confirm="delBatch"
      >
        <el-button slot="reference" style="margin-right: 10px;">批量删除</el-button>
      </el-popconfirm>
      <el-button type="primary" @click="exportExcel" style="margin-right: 10px;">导出用户信息</el-button>
      <el-button type="primary" @click="importExcel">导入用户信息</el-button>
      <input type="file" ref="uploadExcel" style="display: none" @change="handleExcelUpload($event.target.files[0])">
    </div>

    <el-table
        class="xw-block-table"
        :data="tableData"
        border
        @selection-change="handleSelectionChange"
        style="width: 100%">
      <el-table-column
          type="selection"
          width="55">
      </el-table-column>
      <el-table-column
          prop="nickName"
          label="昵称"
      >
      </el-table-column>
      <el-table-column
          prop="nickName"
          label="图像"
      >
        <template slot-scope="scope">
          <el-image style="width: 70px;height: 70px" :src="scope.row.imageUrl"
                    :preview-src-list="[scope.row.imageUrl]" fit="cover"></el-image>
        </template>
      </el-table-column>
      <el-table-column
          prop="age"
          label="年龄"
      >
      </el-table-column>
      <el-table-column
          prop="userName"
          label="用户名"
      >
      </el-table-column>
      <el-table-column
          prop="email"
          label="邮箱"
      >
      </el-table-column>
      <el-table-column
          prop="phone"
          label="联系方式"
      >
      </el-table-column>
      <el-table-column
          label="角色"
      >
        <template slot-scope="scope">
          <el-tag type="success">{{scope.row.role}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
          label="操作"
          width="200">
        <template slot-scope="scope">
          <el-button size="small" @click="edit(scope.row)">编辑</el-button>
          <el-popconfirm
              style="margin-left: 5px"
              confirm-button-text="确定"
              cancel-button-text="我再想想"
              icon="el-icon-info"
              icon-color="red"
              title="您确定要删除吗？"
              @confirm="del(scope.row.id)"
          >
            <el-button slot="reference" size="small">删除</el-button>
          </el-popconfirm>


        </template>
      </el-table-column>
    </el-table>

    <div class="xw-block">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :page-sizes="pageSizeArr"
          :page-size="100"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>

    <MyDrawer ref="MyDrawer" :title="selectRow.id ? '更新' : '新增'" @saveOrUpdate="saveOrUpdate" @close="load" >
      <el-form
          ref="userForm"
          :model="selectRow"
          :rules="formRules"
          class="line"
          label-position="top"
      >
        <el-form-item label="用户头像">
          <el-upload
              class="avatar-uploader"
              :action="baseURL() + '/file/upload'"
              :show-file-list="false"
              :on-success="handleAvatarSuccess">
            <img v-if="selectRow.imageUrl" :src="selectRow.imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="昵称" prop="nickName">
          <el-input placeholder="请输入昵称" v-model="selectRow.nickName"></el-input>
        </el-form-item>
        <el-form-item label="用户名" prop="userName">
          <el-input placeholder="请输入用户名" v-model="selectRow.userName"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input placeholder="请输入邮箱" v-model="selectRow.email"></el-input>
        </el-form-item>
        <el-form-item label="联系方式">
          <el-input placeholder="请输入联系方式" v-model="selectRow.phone"></el-input>
        </el-form-item>
        <el-form-item label="年龄">
          <el-input placeholder="请输入年龄" type="number" v-model="selectRow.age"></el-input>
        </el-form-item>
        <el-form-item label="角色信息" prop="role">
          <el-autocomplete
              style="width: 100%"
              clearable
              placeholder="请选择角色信息"
              v-model="selectRow.role"
              value-key="name"
              :fetch-suggestions="handleRoleFetch"
              @select="handleRoleSelect"
          >
            <template slot-scope="{ item }">
              <div style="display: flex; justify-content: space-between;">
                <span>{{ item.name }}</span>
                <span>{{ item.remark }}</span>
              </div>
            </template>
          </el-autocomplete>
        </el-form-item>
      </el-form>
    </MyDrawer>


  </div>
</template>
<script>
import MyDrawer from "@/components/MyDrawer.vue"

export default {
  data() {
    return {
      delIds: [],
      selectRow: {},
      pageSizeArr: [10, 20, 30, 40],
      tableData: [],
      pageRequest: {
        pageNum: 1,
        pageSize: 10,
        q: {
          nickName: ''
        }
      },
      total: 0,
      formRules: {
        nickName: [
          { required: true, message: '昵称不能为空', trigger: 'blur' }
        ],
        userName: [
          { required: true, message: '用户名不能为空', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '邮箱不能为空', trigger: 'blur' },
          {
            pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
            message: '请输入有效的邮箱地址',
            trigger: 'blur'
          }
        ],
        phone: [
          {
            validator: (rule, value, callback) => {
              if (value && !/^\d{11}$/.test(value)) {
                callback(new Error('请输入11位数字的电话号码'));
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }
        ],
        age: [
          {
            validator: (rule, value, callback) => {
              if (value && (value < 0 || value > 120)) {
                callback(new Error('请输入合理的年龄'));
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }
        ],
        role: [
          { required: true, message: '角色信息不能为空', trigger: 'blur' }
        ]
      }
    };
  },

  components: {MyDrawer},
  mounted() {
    this.load()
  },
  methods: {

    importExcel() {
      this.$refs.uploadExcel.click();
    },

    handleExcelUpload(file) {
      // 清空文件上传框的值
      this.$refs.uploadExcel.value = null;

      const formData = new FormData();
      formData.append('file', file);

      this.request.post("/user/importExcel", formData, {
        headers: { 'Content-Type': 'multipart/form-data' }
      }).then(res => {
        if (res.code === '200') {
          this.messageSuccess("导入成功");
          this.load(); // 导入成功后刷新界面
        } else {
          // 处理返回的错误信息，这里是邮箱已存在的情况
          this.messageError(res.msg);  // 显示“以下邮箱已存在，跳过插入该用户”
          this.load();  // 邮箱已存在时刷新界面，确保数据同步
        }
      }).catch(err => {
        this.messageError('导入失败');
      });
    },




    handleRoleFetch(queryString, cb) {
      this.request.get("/role/selectAll").then(res => {
        if (res.code === '200') {
          cb(res.data)
        }
      })
    },
    handleRoleSelect(e) {
      console.log("handleRoleSelect", e)
    },
    handleAvatarSuccess(e) {
      if (e.code === '200') {
        this.selectRow.imageUrl = e.data
        this.$forceUpdate()
      }
    },
    add() {
      this.selectRow = {}; // 清空当前表单数据
      if (this.$refs.userForm) {
        this.$refs.userForm.resetFields(); // 重置表单验证状态
      }
      this.$refs.MyDrawer.open(); // 打开抽屉
    },
    edit(row) {
      this.selectRow = { ...row }; // 填充需要编辑的数据
      if (this.$refs.userForm) {
        this.$refs.userForm.resetFields(); // 重置表单验证状态
      }
      this.$refs.MyDrawer.open(); // 打开抽屉
    },
    del(id) {
      this.request.delete("/user/" + id).then(res => {
        if (res.code === '200') {
          this.messageSuccess("删除成功")
          this.load()
        } else {
          this.messageError("删除失败")
        }
      })
    },
    delBatch() {
      if (this.delIds && this.delIds.length > 0) {
        this.request.post("/user/deleteBatchByIds", this.delIds).then(res => {
          if (res.code === '200') {
            this.messageSuccess("删除成功")
            this.load()
          } else {
            this.messageError("删除失败")
          }
        })
      } else {
        this.messageError("请先勾选数据")
      }
    },
    saveOrUpdate() {
      this.$refs.userForm.validate((valid) => {
        if (valid) {
          if (!this.selectRow.imageUrl) {
            this.selectRow.imageUrl = 'https://img2.baidu.com/it/u=2625169353,2769422191&fm=253&fmt=auto?w=800&h=800'; // 默认头像地址
          }
          this.request.post("/user/saveOrUpdate", this.selectRow).then(res => {
            if (res.code === '200') {
              if (!this.selectRow.id) {
                this.messageSuccess(`操作成功,初始密码为123456`);
              } else {
                this.messageSuccess("操作成功");
              }
              this.$refs.MyDrawer.close();
              this.load();
            } else {
              this.messageError(res.msg);
            }
          });
        } else {
          this.messageError('请检查必填项是否填写完整');
        }
      });
    },


    // 清空搜索
    clearSearch() {
      this.menuName = '';
      this.load(); // 可选：清空后重新加载数据
    },

    exportExcel() {
      this.request.get("/user/exportExcel", { responseType: 'blob' }).then(res => {
        const blob = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
        const link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = '用户数据.xlsx';
        link.click();
      }).catch(err => {
        this.messageError('导出失败');
      });
    },

    load() {
      this.request.post("/user/page", this.pageRequest).then(res => {
        if (res.code === '200') {
          this.tableData = res.data.list
          this.total = res.data.total
        }
      })
    },
    handleSizeChange(size) {
      this.pageRequest.pageSize = size
      this.load()
    },
    handleCurrentChange(pageNum) {
      this.pageRequest.pageNum = pageNum
      this.load()
    },
    handleSelectionChange(e) {
      this.delIds = e.map(x => x.id)
    }
  }

}
</script>